"""
Image Utilities
图像处理工具函数
"""

import os
import logging
from typing import Optional
from PIL import Image

logger = logging.getLogger(__name__)


def load_image(image_path: str) -> Optional[Image.Image]:
    """
    加载图像并处理异常
    
    Args:
        image_path: 图像文件路径
        
    Returns:
        Optional[Image.Image]: PIL图像对象，失败时返回None
    """
    try:
        if not os.path.exists(image_path):
            logger.error(f"图像文件不存在: {image_path}")
            return None
        
        image = Image.open(image_path)
        
        # 转换为RGB格式
        if image.mode != 'RGB':
            image = image.convert('RGB')
        
        logger.info(f"成功加载图像: {image_path}")
        return image
        
    except Exception as e:
        logger.error(f"加载图像失败 {image_path}: {e}")
        return None


def preprocess_image(image: Image.Image, target_size: tuple = (224, 224)) -> Image.Image:
    """
    图像预处理
    
    Args:
        image: PIL图像对象
        target_size: 目标尺寸
        
    Returns:
        Image.Image: 预处理后的图像
    """
    try:
        # 调整图像大小
        if image.size != target_size:
            image = image.resize(target_size, Image.Resampling.LANCZOS)
        
        return image
        
    except Exception as e:
        logger.error(f"图像预处理失败: {e}")
        return image
